package com.lw.nio.channel.fileChannel;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author LW
 * @2021/9/12 18:13
 */
public class FileChannelDemo1 {
    /**
     * 需要解决读取中文乱码问题
     * @param args
     * @throws Exception
     */
    //FileChannel读取数据到buufer中
    public static void main(String[] args) throws Exception {

        //创建FileChannel
        RandomAccessFile aFile = new RandomAccessFile("C:\\Users\\ASUS\\Desktop\\gdmp.txt", "rw");
        FileChannel channel = aFile.getChannel();

        //创建Buffer
        ByteBuffer buf = ByteBuffer.allocate(1024);


        //读取数据到buffer中
        int read = channel.read(buf);
        while(read != -1) {//等于-1即到了文件的末尾
            System.out.println("读取了：" + read);
            buf.flip();//翻转看看是否读数据进了buffer
            while (buf.hasRemaining()) {//看看有没有剩余的
                System.out.println((char)buf.get());//有就获取
            }
            buf.clear();
            read = channel.read(buf);
        }
        aFile.close();
        System.out.println("结束了");
    }
}
